package com.cap.bts.crmdp.dealer.masterinfo.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cap.bts.commonfunc.common.util.DateUtil;
import com.cap.bts.crmdp.dealer.masterinfo.constants.MasterInfoConstants;
import com.cap.bts.crmdp.dealer.masterinfo.dao.IMasterFileDao;
import com.cap.bts.crmdp.dealer.masterinfo.dao.IOtherProductDao;
import com.cap.bts.crmdp.dealer.masterinfo.dao.IServiceInfoDefDao;
import com.cap.bts.crmdp.dealer.masterinfo.dao.ITyreProductDao;
import com.cap.bts.crmdp.dealer.masterinfo.domain.MasterFileModel;
import com.cap.bts.crmdp.dealer.masterinfo.domain.OtherProductModel;
import com.cap.bts.crmdp.dealer.masterinfo.domain.ServiceInfoDefModel;
import com.cap.bts.crmdp.dealer.masterinfo.domain.TyreProductModel;
import com.cap.bts.crmdp.dealer.masterinfo.dto.MaeterInfoDto;
import com.cap.bts.crmdp.dealer.masterinfo.dto.MasterFileDto;
import com.cap.bts.crmdp.dealer.masterinfo.service.IMasterInfoService;
import com.cap.bts.crmdp.dealer.masterinfo.utils.MasterInfoUtils;
import com.cap.bts.crmdp.httpconnection.HttpConnectionUtils;
import com.cap.bts.framework.codemapping.domain.CodeInfo;
import com.cap.bts.framework.codemapping.service.ICodeMapping;
import com.cap.bts.framework.common.constant.CommonErrorConstants;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.service.impl.BaseServiceImpl;

@Transactional(rollbackFor = AppException.class)
@Service
public class MasterInfoServiceImpl extends BaseServiceImpl implements IMasterInfoService {

//    private static final Logger logger = Logger.getLogger(MasterInfoServiceImpl.class);

    @Autowired
    ITyreProductDao             iTyreProductDao;

    @Autowired
    IOtherProductDao            iOtherProductDao;

    @Autowired
    IServiceInfoDefDao          iServiceInfoDefDao;

    @Autowired
    IMasterFileDao              iMasterFileDao;

    @Autowired
    ICodeMapping                iCodeMapping;

   /* @Override
    public TyreProductModel insertTyreProductInfo(TyreProductModel tyreProductModel)
                                                                                    throws AppException {
        return iTyreProductDao.insertTyreProductInfo(tyreProductModel);
    }

    @SuppressWarnings("rawtypes")
    @Override
    public void removeTyreProduct() throws AppException {
        List<TyreProductModel> tyreProductList = getAllTyreProduct();
        if (!tyreProductList.isEmpty()) {
            for (Iterator iterator = tyreProductList.iterator(); iterator.hasNext();) {
                TyreProductModel tyreProductModel = (TyreProductModel) iterator.next();
                iTyreProductDao.removeTyreProduct(tyreProductModel);
            }
        }
    }
*/
    @Override
    public List<TyreProductModel> getAllTyreProduct() throws AppException {
        return iTyreProductDao.getAllTyreProduct();
    }
    
    
    @Override
    public List<OtherProductModel> getAllTOtherProduct() throws AppException {
        return iOtherProductDao.getAllTOtherProduct();
    }
/*
    @Override
    public OtherProductModel insertOtherProductInfo(OtherProductModel otherProductModel)
                                                                                        throws AppException {
        return iOtherProductDao.insertOtherProductInfo(otherProductModel);
    }

    @SuppressWarnings("rawtypes")
    @Override
    public void removeOtherProduct() throws AppException {
        List<OtherProductModel> otherProductList = getAllTOtherProduct();
        if (!otherProductList.isEmpty()) {
            for (Iterator iterator = otherProductList.iterator(); iterator.hasNext();) {
                OtherProductModel otherProductModel = (OtherProductModel) iterator.next();
                iOtherProductDao.removeOtherProduct(otherProductModel);
            }
        }
    }

    

    @Override
    public ServiceInfoDefModel insertServiceInfo(ServiceInfoDefModel serviceInfoDefModel)
                                                                                         throws AppException {
        return iServiceInfoDefDao.insertServiceInfo(serviceInfoDefModel);

    }

    @SuppressWarnings("rawtypes")
    @Override
    public void removeServiceInfoDef() throws AppException {
        List<ServiceInfoDefModel> serviceInfoDefList = getAllServiceInfoDef();
        if (!serviceInfoDefList.isEmpty()) {
            for (Iterator iterator = serviceInfoDefList.iterator(); iterator.hasNext();) {
                ServiceInfoDefModel serviceInfoDefModel = (ServiceInfoDefModel) iterator.next();
                iServiceInfoDefDao.remove(serviceInfoDefModel);
            }
        }
    }

    */
    @Override
    public List<ServiceInfoDefModel> getAllServiceInfoDef() throws AppException {
        return iServiceInfoDefDao.getAllServiceInfoDef();
    }
    
   /* @SuppressWarnings({ "rawtypes", "unchecked" })
    @Override
    public void checkSaveInfo(Map<String, Object> resultMap, MaeterInfoDto dto) throws AppException {

        if (MasterInfoConstants.SYNCHRONIZATIONMETHOD_FULL.equals(dto.getSynchronizationMethod())) {
            if (MasterInfoConstants.FILE_TYPE_TYREPRODUCTFILE.equals(dto.getFileType())) {//轮胎文件
                removeTyreProduct();
            } else if (MasterInfoConstants.FILE_TYPE_OTHERPRODUCTFILE.equals(dto.getFileType())) {//非轮胎文件
                removeOtherProduct();
            } else if (MasterInfoConstants.FILE_TYPE_SERVICEFILE.equals(dto.getFileType())) {//服务文件
                removeServiceInfoDef();
            }
        }

        try {
            Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("data");
            if (!dataMap.isEmpty()) {
                for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
                    List dataList = (List) entry.getValue();
                    for (Iterator iterator = dataList.iterator(); iterator.hasNext();) {
                        Map<String, Object> map = (Map<String, Object>) iterator.next();

                        logger.info("数据map:" + map);
                        if (MasterInfoConstants.FILE_TYPE_TYREPRODUCTFILE.equals(dto.getFileType())) {//轮胎文件

                            TyreProductModel tyreProductModel = (TyreProductModel) MasterInfoUtils
                                .convertMap(TyreProductModel.class, map);
                            List<TyreProductModel> tyreProductList = iTyreProductDao
                                .getTyreProductList(tyreProductModel.getMfgrCode());
                            if (tyreProductList == null || tyreProductList.isEmpty()) {
                                insertTyreProductInfo(tyreProductModel);
                            } else {
                                iTyreProductDao.updateTyreProductInfo(tyreProductModel,
                                    tyreProductList.get(0).getId());
                            }
                        } else if (MasterInfoConstants.FILE_TYPE_OTHERPRODUCTFILE.equals(dto
                            .getFileType())) {//非轮胎文件

                            OtherProductModel otherProductModel = (OtherProductModel) MasterInfoUtils
                                .convertMap(OtherProductModel.class, map);
                            List<OtherProductModel> otherProductList = iOtherProductDao
                                .getOtherProductList(otherProductModel.getMfgrCode());
                            if (otherProductList == null || otherProductList.isEmpty()) {
                                insertOtherProductInfo(otherProductModel);
                            } else {
                                iOtherProductDao.updateOtherProductInfo(otherProductModel,
                                    otherProductList.get(0).getId());
                            }
                        } else if (MasterInfoConstants.FILE_TYPE_SERVICEFILE.equals(dto
                            .getFileType())) {//服务文件

                            ServiceInfoDefModel serviceInfoDefModel = (ServiceInfoDefModel) MasterInfoUtils
                                .convertMap(ServiceInfoDefModel.class, map);
                            List<ServiceInfoDefModel> serviceInfoDefList = iServiceInfoDefDao
                                .getServiceInfoDefList(serviceInfoDefModel.getCode());
                            if (serviceInfoDefList == null || serviceInfoDefList.isEmpty()) {
                                insertServiceInfo(serviceInfoDefModel);
                            } else {
                                iServiceInfoDefDao.updateServiceInfoDefinfo(serviceInfoDefModel,
                                    serviceInfoDefList.get(0).getId());
                            }
                        }
                    }
                }
            }

            
            //保存新数据的文件属性
            List<Map<String, Object>> fileNameList = (List) resultMap.get("fileNameList");
            if (!fileNameList.isEmpty()) {
                for (Iterator iterator = fileNameList.iterator(); iterator.hasNext();) {
                    Map<String, Object> map = (Map<String, Object>) iterator.next();
                    String fileName = (String) map.get("fileName");

                    MasterFileDto masterFileDto = new MasterFileDto();
                    masterFileDto.setFileType(dto.getFileType());
                    masterFileDto.setFileName(fileName);

                    insertMasterFileInfo(masterFileDto);
                }
            }
        } catch (Exception e) {
            throw new AppException(CommonErrorConstants.SYSTEM_ERROR, e);
        }
    }
*/
    /*@Override
    public void removeAllTyreProductInfo() throws AppException {
        iTyreProductDao.removeAllTyreProductInfo();
    }*/

    /**
     * 根据文件名称查询已经同步过的master文件
     * @see com.cap.bts.crmdp.dealer.masterinfo.service.IMasterInfoService#getMasterFileInfoByFileName(com.cap.bts.crmdp.dealer.masterinfo.dto.MasterFileDto)
     */
  /*  @Override
    public MasterFileModel getMasterFileInfoByFileName(MasterFileDto masterFileDto)
                                                                                   throws AppException {
        MasterFileModel masterFileModel = iMasterFileDao.getMasterFileInfoByFileName(masterFileDto);
        if (masterFileModel != null) {
            return masterFileModel;
        }
        return null;

    }*/

    /**
     * 保存同步的文件属性信息
     * @see com.cap.bts.crmdp.dealer.masterinfo.service.IMasterInfoService#insertMasterFileInfo(com.cap.bts.crmdp.dealer.masterinfo.dto.MasterFileDto)
     */
  /*  @Override
    public MasterFileModel insertMasterFileInfo(MasterFileDto masterFileDto) throws AppException {

        MasterFileModel masterFileModel = new MasterFileModel();
        masterFileModel.setFileType(masterFileDto.getFileType());
        masterFileModel.setFileName(masterFileDto.getFileName());

        iMasterFileDao.insertMasterFileInfo(masterFileModel);
        return masterFileModel;
    }*/

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年12月1日
     * @see com.cap.bts.crmdp.dealer.masterinfo.service.IMasterInfoService#deleteTyreProductInfo(com.cap.bts.crmdp.dealer.masterinfo.domain.TyreProductModel)
    **/
   /* @Override
    public void deleteTyreProductInfo(TyreProductModel model) throws AppException {
        iTyreProductDao.remove(model.getId());
    }*/

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年12月1日
     * @see com.cap.bts.crmdp.dealer.masterinfo.service.IMasterInfoService#getTyreProductInfoByMfgrCode(java.lang.String)
    **/
  /*  @Override
    public List<TyreProductModel> getTyreProductInfoByMfgrCode(String mfgrCode) throws AppException {
        return iTyreProductDao.getTyreProductInfoByMfgrCode(mfgrCode);
    }*/
/*
	@Override
	public void getOpenHttpConnect(MaeterInfoDto dto) throws AppException {
		//根据code查询出查询文件的地址
        CodeInfo codeInfo = iCodeMapping
            .getCodeInfoByCode(MasterInfoConstants.MASTER_INFO_QUERY_FILEPATH);
        String urlPath;
        if (codeInfo != null) {
            urlPath = codeInfo.getValue();
        } else {
            throw new AppException("error", "文件查询地址获取失败");
        }
        String charset = "UTF-8";
        int connectTimeout = 6000;
        int readTimeout = 6000;
        urlPath += "fileType=" + dto.getFileType();
        try {
            String result = HttpConnectionUtils.openHttpsConnection(urlPath, charset,
                connectTimeout, readTimeout, null);
            logger.info("获取到的文件信息：" + result);

            List<CodeInfo> masterInfoTypeList = iCodeMapping
                .getCodeInfoByType(MasterInfoConstants.MASTER_INFO_FILETYPE);
            for (Iterator iterator = masterInfoTypeList.iterator(); iterator.hasNext();) {
                CodeInfo codeInfo2 = (CodeInfo) iterator.next();
                Map<String, Object> resultMap = getFileInfo(result, codeInfo2.getType(),
                    MasterInfoConstants.SYNCHRONIZATIONMETHOD_INCREMENT);
                checkSaveInfo(resultMap, dto);
            }
        } catch (Exception e) {
            logger.error("提取信息失败", e);

        }
	}
*/
	/*@Override
	public Map<String, Object> getFileInfo(String result, String fileType, String synchronizationMethod)
			throws AppException {
		JSONObject jsonObject = JSONObject.parseObject(result);
        String status = jsonObject.getString("status");
        String message = jsonObject.getString("message");
        Map<String, Object> dataMap = null;
        
        List<Map<String, Object>> resultList = new ArrayList();
        if ("200".equals(status) && "ok".equals(message)) {
            String dataString = jsonObject.getString("data");

            JSONArray jsonArray = JSONArray.parseArray(dataString);

            String currentDte = DateUtil.getDateText(new Date());
            //本地存储目录
            String localFilePath = MasterInfoConstants.getLOCALHOSTPATH_STRING() + fileType + "/"
                                   + currentDte + "/";

            int num = 0;
            dataMap = new HashMap<String, Object>();
            for (Iterator iterator = jsonArray.iterator(); iterator.hasNext();) {
                JSONObject object = (JSONObject) iterator.next();
                String fileName = object.getString("fileName");//获取文件下载的名称
                String fileUrl = object.getString("fileUrl");//获取文件下载的地址

                //增量同步Master数据
                if (MasterInfoConstants.SYNCHRONIZATIONMETHOD_INCREMENT
                    .equals(synchronizationMethod)) {
                    //判断该文件是否已经被同步过
                    MasterFileDto masterFileDto = new MasterFileDto();
                    masterFileDto.setFileName(fileName);
                    MasterFileModel masterFileModel = getMasterFileInfoByFileName(masterFileDto);

                    if (masterFileModel != null) {
                        continue;
                    }
                }
                fileName = fileName.substring(0, fileName.indexOf(".csv"));

                //根据code查询出需要文件下载的URL地址
                CodeInfo codeInfo = iCodeMapping
                    .getCodeInfoByCode(MasterInfoConstants.MASTER_INFO_DOWNLOAD_FILEPATH);

                String urlPath = null;
                if (codeInfo != null) {
                    urlPath = codeInfo.getValue() + fileUrl;
                }
                File csvFile = null;
                if (urlPath != null && localFilePath != null && fileName != null) {
                    try {
                        csvFile = HttpConnectionUtils.downloadFile(urlPath, localFilePath, fileName);
                    } catch (IOException e) {
                        throw new AppException("getFileInfo", e);
                    }
                }
                List<String> list = MasterInfoUtils.analyzeCsv(csvFile);
                List<Map<String, Object>> dataList = MasterInfoUtils.combinationList(list);
                dataMap.put("dataList" + num, dataList);
                
                Map<String, Object> fileNameMap = new HashMap<String, Object>();
                fileNameMap.put("fileName", fileName + ".csv");
                resultList.add(num, fileNameMap);
                
                num++;
            }

        }

        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("data", dataMap);
        resultMap.put("fileNameList", resultList);

        return resultMap;
	}*/

	/*@Override
	public void processSynchronizationDataFromWecare() throws AppException {
		try {
			List<MaeterInfoDto> masterInfoDtoList = new ArrayList<MaeterInfoDto>();
			MaeterInfoDto tyre = new MaeterInfoDto();
			MaeterInfoDto otherProduct = new MaeterInfoDto();
			MaeterInfoDto service = new MaeterInfoDto();
			tyre.setFileType(MasterInfoConstants.FILE_TYPE_TYREPRODUCTFILE);
			tyre.setSynchronizationMethod("increment");
			otherProduct.setFileType(MasterInfoConstants.FILE_TYPE_OTHERPRODUCTFILE);
			otherProduct.setSynchronizationMethod("increment");
			service.setFileType(MasterInfoConstants.FILE_TYPE_SERVICEFILE);
			service.setSynchronizationMethod("increment");
			masterInfoDtoList.add(tyre);
			masterInfoDtoList.add(otherProduct);
			masterInfoDtoList.add(service);
			for(int i=0; i<masterInfoDtoList.size(); i++){
				final MaeterInfoDto dto = masterInfoDtoList.get(i);

			    getOpenHttpConnect(dto);
			}

		} catch (Exception e) {
			throw new AppException("Exception processSynchronizationDataFromWecare", e);
		}
	}*/
    
}
